<template>
  <div class="eleTableWrap">
    <!-- 通用工具条 -->
    <div class="btns-wrap">
      <!-- 筛选展示的列 -->
      <el-popover placement="bottom" width="70" trigger="hover">
        <el-checkbox-group v-model="selCols">
          <el-checkbox :label="name" v-for="(name, i) in colList" :key="i"></el-checkbox>
        </el-checkbox-group>
        <el-button type="primary" size="mini" slot="reference" icon="el-icon-finished"></el-button>
      </el-popover>
      <!-- 打印按钮 -->
      <el-button type="primary" size="mini" icon="el-icon-printer" @click="print"></el-button>
    </div>
    <!-- 如果需要固定表头，直接添加属性：height="300" -->
    <el-table stripe size="mini" border :data="tableData" show-overflow-tooltip ref="multipleTable" @selection-change="handleSelectionChange" @sort-change="handleSort" v-loading="loading" id="myTable">
      <!-- 复选框列 -->
      <el-table-column type="selection" width="60" align="center">
      </el-table-column>
      <!-- 序列 -->
      <el-table-column type="index" label="序号" width="60" fixed align="center">
      </el-table-column>
      <!-- 内容列，根据数据动态生成 -->
      <template v-for="obj in tableHeaders">
        <el-table-column :prop="obj.key" :label="obj.name" :width="obj.width" :sortable="obj.sortable" v-if="obj.show" :key="obj.key">
        </el-table-column>
      </template>
      <!-- 自定义列 -->
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click.stop="edit(scope.row)">编辑</el-button>
          <el-button type="primary" icon="el-icon-download" size="mini" @click.stop="download(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页板块 -->
    <div class="pagination-wrap">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.curPage" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
// Author: Yanyun Bai
// 饿了么组件库表格示例组件（依赖DM平台中的自定义组件：global.vue）

// 饿了么table组件官方文档：
// https://element.eleme.cn/#/zh-CN/component/table

export default {
  name: 'ele-table',
  data() {
    return {
      loading: false,
      multipleSelection: [], // 存储选择的行
      tableData: [],  // 表格数据
      // 表格列设置，这里有很多有用的设置
      tableHeaders: [
        { key: 'name', name: '姓名', width: 200, show: true, sortable: 'custom' },
        { key: 'province', name: '省份', width: 200, show: true, sortable: 'custom' },
        { key: 'city', name: '城市', width: 200, show: true, sortable: 'custom' },
        { key: 'address', name: '地址', width: 200, show: true, sortable: 'custom' },
        { key: 'zip1', name: '邮编1', width: 200, show: true, sortable: 'custom' },
        { key: 'zip2', name: '邮编2', width: 200, show: true, sortable: 'custom' },
        { key: 'zip3', name: '邮编3', width: 200, show: true, sortable: 'custom' },
        { key: 'zip4', name: '邮编4', width: 200, show: true, sortable: 'custom' },
      ],
      // 筛选列
      selCols: [],
      pagination: {
        curPage: 1,
        pageSize: 10,
        total: 100
      }
    }
  },
  computed: {
    // 筛选列的列表
    colList() {
      return this.tableHeaders.map(obj => obj.name)
    }
  },
  mounted() {
    this.getData();
    // 初始化全选所有列
    this.selCols = this.tableHeaders.map(obj => obj.name)
    // 监听search按钮释放的事件
    this.bus.$on('refreshTable', (obj) => {
      this.getData(obj)
    })
  },
  methods: {
    // 获取列表数据
    // obj是筛选条件
    getData(obj) {
      console.log(obj)
      this.loading = true;
      this.tableData = Array.from({ length: 10 }, () => {
        return {
          name: '王小虎',
          province: '上海',
          city: '普陀区',
          address: '上海市普陀区金沙江路 1518 弄',
          zip1: parseInt(Math.random() * 100),
          zip2: 31932713713693749238,
          zip3: 31932713713693749238,
          zip4: 31932713713693749238,
        }
      });
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    },
    // 列表排序
    handleSort({ column, prop, order }) {
      console.log({ column, prop, order })
      this.getData()
    },
    // 处理复选框选择事件
    handleSelectionChange(rows) {
      this.multipleSelection = rows
    },
    edit(row) {
      console.log(row)
    },
    download(row) {
      console.log(row)
    },
    print() {
      // window.print();
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none'
      document.body.appendChild(iframe);
      iframe.contentWindow.document.write(`<div>${document.querySelector('#myTable').innerHTML}</div>`);
      iframe.contentWindow.print();
      document.body.removeChild(iframe);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.getData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getData()
    }
  },
  watch: {
    selCols: {
      // 动态改变列
      handler: function (n, o) {
        this.tableHeaders.forEach((col) => {
          n.includes(col.name) ? col.show = true : col.show = false
          // 必须加这句，否则表格会闪动或样式出错
          this.$nextTick(() => {
            this.$refs.multipleTable.doLayout()
          })
        })
      },
      deep: true
    }
  }

}
</script>
<style>
.eleTableWrap {
  margin-top: 20px;
  margin-left: 25px;
  margin-right: 25px;
}

.btns-wrap {
  text-align: right;
  margin-bottom: 15px;
}

.btns-wrap>.el-button {
  margin-left: 15px;
}

/* 设置表头颜色 */
.eleTableWrap .el-table th {
  background: #f4f4f5;
}

.pagination-wrap {
  margin-top: 20px;
  text-align: right;
}

/* vuetify样式影响了饿了么分页组件的样式，这里抵消影响 */
.pagination-wrap .el-pager {
  padding-left: unset !important;
}
</style>